import 'package:deer/order/order_list.dart';
import 'package:deer/res/colors.dart';
import 'package:deer/res/font.dart';
import 'package:deer/res/styles.dart';
import 'package:deer/util/utils.dart';
import 'package:deer/widgets/my_card.dart';
import 'package:deer/widgets/my_flexible_space_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class Order extends StatefulWidget {
  const Order({Key key, this.color: Colors.orange}) : super(key: key);
  final Color color;
  @override
  _OrderState createState() => _OrderState();
}

class _OrderState extends State<Order>
    with AutomaticKeepAliveClientMixin<Order>, SingleTickerProviderStateMixin {
  /*
  Flutter切换tab后保留tab状态 概述 Flutter中为了节约内存不会保存widget的状态,widget都是临时变量。
  添加AutomaticKeepAliveClientMixin，并设置为true,这样就能一直保持当前不被initState了。
  */
  @override
  bool get wantKeepAlive => true;

  TabController _tabController;
  int _index = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 5);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  bool _isPageCanChange = true;
  PageController _pageController = PageController(initialPage: 0);
  _onPageChange(int index, {PageController p, TabController t}) async {
    if (p != null) {
      // 判断是哪一个切换
      _isPageCanChange = false;
      //等待pageview切换完毕,再释放pageivew监听
      await _pageController.animateToPage(index,
          duration: Duration(milliseconds: 300), curve: Curves.ease);
      _isPageCanChange = true;
    } else {
      _tabController.animateTo(index);
    }

    _index = index;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: NestedScrollView(
        physics: ClampingScrollPhysics(),
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return _sliverBuilder(context);
        },
        body: PageView.builder(
          itemCount: 5,
          onPageChanged: (index) { // 监听位置
            if (_isPageCanChange) {
              _onPageChange(index);
            }
          },
          controller: _pageController,
          itemBuilder: (_, index) {
            return OrderList(index: index, tabIndex: _index,);
          },
        ),
      ),
    );
  }

  List<Widget> _sliverBuilder(BuildContext context) {
    return <Widget>[
      SliverOverlapAbsorber(
        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        child: SliverAppBar(
          actions: <Widget>[
            IconButton(
              icon: Image.asset(
                Utils.getImagePath('order/icon_search'),
                width: 22,
                height: 22,
              ),
              onPressed: () {},
            )
          ],
          backgroundColor: Colors.transparent,
          elevation: 0.0,
          expandedHeight: 100,
          floating: false, // 不随着滑动隐藏标题
          pinned: true, // 固定在顶部
          centerTitle: true,
          flexibleSpace: MyFlexibleSpaceBar(
            title: Text('订单'),
            centerTitle: true,
            titlePadding:
                const EdgeInsetsDirectional.only(start: 16, bottom: 14),
            collapseMode: CollapseMode.pin,
            background: Image.asset(Utils.getImagePath('order/order_bg'),
                width: double.infinity, height: 113, fit: BoxFit.fill),
          ),
        ),
      ),
      //就是给一个可滑动的视图添加一个头
      //实际上，在CustomScrollView的slivers列表中，header可以出现在视图的任意位置，不一定要是在顶部
      SliverPersistentHeader(
        pinned: true, // 固定
        delegate: SliverAppBarDelegate(
            DecoratedBox(
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                        Utils.getImagePath('order/order_bg1'),
                      ),
                      fit: BoxFit.fill)),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: MyCard(
                  child: Container(
                    height: 80,
                    child: TabBar(
                      controller: _tabController,
                      labelColor: Colours.text_dark,
                      labelStyle: TextStyles.textDark14,
                      indicatorColor: Colors.transparent,
                      labelPadding: const EdgeInsets.only(top: 8),
                      tabs: <Widget>[
                        _myTabItem(0, "order/xdd_s", "order/xdd_n", '新订单'),
                        _myTabItem(1, "order/dps_s", "order/dps_n", '待配送'),
                        _myTabItem(2, "order/dwc_s", "order/dwc_n", '待完成'),
                        _myTabItem(3, "order/ywc_s", "order/ywc_n", '已完成'),
                        _myTabItem(4, "order/yqx_s", "order/yqx_n", '已取消'),
                      ],
                      onTap: (index) {
                        if (!mounted) {
                          return;
                        }
                        _pageController.jumpToPage(index);
                        _index = index;
                        setState(() {});
                      },
                    ),
                  ),
                ),
              ),
            ),
            80),
      )
    ];
  }

  Widget _myTabItem(int index, String selImg, String unImg, String text) {
    return Stack(
      children: <Widget>[
        Container(
          width: 46,
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Image.asset(
                Utils.getImagePath(_index == index ? selImg : unImg),
                width: 24,
                height: 24,
              ),
              Gaps.vGap(8),
              Text(text),
            ],
          ),
        ),
        Positioned(
          right: 0,
          child: index < 3
              ? DecoratedBox(
                  decoration: BoxDecoration(
                      color: Colours.text_red,
                      borderRadius: BorderRadius.circular(11)),
                  child: Padding(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                    child: Text('10',
                        style: TextStyle(
                            color: Colors.white, fontSize: Font.font_sp12)),
                  ),
                )
              : Gaps.empty,
        )
      ],
    );
  }
}

/*
自定义SliverPersistentHeaderDelegate很简单，
只需重写build()、get maxExtent、get minExtent和shouldRebuild()这四个方法
*/
class SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget widget;
  final double height;
  SliverAppBarDelegate(this.widget, this.height);

  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return widget;
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
